package org.al.poc.webserver.functional;

import java.io.IOException;
import java.net.ServerSocket;

import org.al.poc.persistence.beans.Connection;
import org.al.poc.persistence.beans.Order;
import org.al.poc.persistence.dao.Connexion;
import org.al.poc.persistence.dao.DaoFactory;
import org.al.poc.persistence.dao.DaoFactory.TypeFabrique;
import org.al.poc.persistence.dao.DaoOrder;
import org.al.poc.sockets.AbstractServerThread;
import org.al.poc.sockets.SocketManager;

public class ServerThread extends AbstractServerThread {
	
	Connexion connexionDB;
	DaoOrder dao;

	public ServerThread(ServerSocket ss) {
		super(ss);
		
		try {
			DaoFactory.setTypeDao(TypeFabrique.JPAOracle);
			DaoFactory factory = DaoFactory.getDaoFactory(null);
			connexionDB = factory.getConnexion();
			dao = factory.getDaoOrder();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}

	
	@Override
	protected void processConnection(Connection connection) {
		
		connection.setSessionId(SessionManager.getNextSessionId());
		SocketManager manager = new SocketManager(socket);
		
		try {
			manager.writeObject(connection);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		LogManager.logConnection();
	}
	
	@Override
	protected void processOrder (Order order) {
		
		try {
			connexionDB.begin();
			dao.create(order);
			connexionDB.commit();
			LogManager.logOrder();
		}
		catch (Exception e) {
			e.printStackTrace();
		}

		SocketManager manager = new SocketManager(socket);
		try {
			manager.writeObject(order);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
